import {
  Breadcrumb,
  Button,
  Form,
  Input,
  Message,
  Tabs,
} from "@arco-design/web-react";
import { css } from "@emotion/css";
import {
  FinalRiskType,
  RiskType,
  SearchRiskTypeParams,
  VideosType,
} from "../../api/types/elder-risk.ts";
import { useAPI } from "../../hooks/useAPI.ts";
import { RiskStatisticCard } from "../../components/RiskStatisticCard";
import { ElderRiskWarningCard } from "../../components/ElderRiskWarningCard";
import { useEffect, useState } from "react";
import { IconRefresh, IconRight } from "@arco-design/web-react/icon";
import { Dayjs } from "dayjs";
import { Link } from "../../components/Link";

const riskPriority = {
  danger: 1,
  warning: 2,
};
type RiskPriorityKeys = keyof typeof riskPriority;

export default function Workspace() {
  const api = useAPI();

  const [formRef] = Form.useForm<any>();
  const [riskType, setRiskType] = useState<RiskType | null>(RiskType.Detail);
  const [search, setSearchValues] = useState("");
  const [data, setData] = useState([]);
  const params: SearchRiskTypeParams = {
    pageNum: 1,
    pageSize: 1000,
  };

  const fetchData = () => {
    if (riskType == null) return; // Skip fetching if riskType is null
    api
      .getElderByRisk({ riskType, search, ...params })
      .then((response) => {
        setData(response.data.data);
      })
      .catch((err) => {
        if (err instanceof Error) {
          Message.error(err.message);
        } else {
          Message.error("操作失败，请稍后重试");
        }
      });
  };
  useEffect(() => {
    fetchData();
    const intervalId = setInterval(() => {
      fetchData();
    }, 5000);
    return () => clearInterval(intervalId);
  }, [riskType, search]);

  return (
    <div>
      <Breadcrumb
        className={css`
          padding: 12px;
          border-radius: 1px;
          font-weight: bold;
          border-left: 5px solid rgb(var(--primary-6));
          margin-bottom: 20px;
        `}
        separator={<IconRight />}
      >
        <Breadcrumb.Item style={{ fontWeight: 400 }}>
          <Link
            to="/homepage/index"
            style={{
              textDecoration: "none",
              transition: "color 0.3s",
              fontWeight: "bold",
              fontSize: "15px",
            }}
          >
            工作台
          </Link>
        </Breadcrumb.Item>
      </Breadcrumb>

      <Form form={formRef} layout={"inline"}>
        <Form.Item label="搜索：" field="key" style={{ marginLeft: "10px" }}>
          <Input.Search
            value={search}
            onChange={(value) => {
              setSearchValues(value);
              // refetch();
            }}
            placeholder="请输入关键字"
            style={{ width: "200px" }}
            allowClear
          />
        </Form.Item>
        <Form.Item>
          <Button
            type="outline"
            htmlType="button"
            onClick={() => {
              formRef.resetFields();
              setSearchValues("");
              // refetch()
            }}
          >
            <IconRefresh />
            重置
          </Button>
        </Form.Item>
      </Form>

      <Tabs
        activeTab={JSON.stringify(riskType)}
        onChange={(key) => setRiskType(JSON.parse(key))}
        style={{ marginTop: "12px" }}
      >
        <Tabs.TabPane key={RiskType.Detail} title="全部风险" />
        <Tabs.TabPane key={RiskType.High} title="高风险" />
        <Tabs.TabPane key={RiskType.Middle} title="中风险" />
        <Tabs.TabPane key={RiskType.None} title="无风险" />
      </Tabs>

      <div
        className={css`
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 20px;
          padding-top: 14px;
        `}
      >
        <RiskStatisticCard />
        {data
          ?.sort(
            (
              a: { actionStatus: string; ownerName: string },
              b: { actionStatus: string; ownerName: string }
            ) => {
              // Assign priority to risk types
              const riskComparison =
                (riskPriority[a.actionStatus as RiskPriorityKeys] || 3) -
                (riskPriority[b.actionStatus as RiskPriorityKeys] || 3);
              if (riskComparison !== 0) {
                return riskComparison;
              }

              // If riskTypes are the same, sort by ownerName.
              // Assume ownerName can be casted to integer
              return (
                parseInt(a.ownerName) - parseInt(b.ownerName)
              );
            }
          )
          .map(
            (
              row: {
                userId: any;
                actionStatus: FinalRiskType;
                ownerName: string;
                ownerId: number;
                info: string;
                videos: VideosType[] | undefined;
                lastAction: string;
                createTime: string | number | Dayjs | undefined;
                isNursing: boolean;
              },
              index: any
            ) => (
              <ElderRiskWarningCard
                key={`${row.userId}${index}`}
                riskType={row.actionStatus}
                name={row.ownerName}
                userId={row.ownerId}
                vitalInfo={row.info ? JSON.parse(row.info) : null}
                videoList={row.videos}
                dictLabel={
                  row.lastAction ? JSON.parse(row.lastAction).actCn : "/"
                }
                time={row.createTime}
                isNursing={row.isNursing}
              />
            )
          )}
      </div>
    </div>
  );
}
